package com.syeet.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author xhl
 * @date 2023/4/21
 */
@Controller
public class LoginController {
    private final String LOGIN_TOKEN = "login:token:";

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 从redis获取token对应的用户信息
     * @param token
     * @return
     */
    @ResponseBody
    @GetMapping("/userinfo")
    public String userinfo(@RequestParam(value = "token") String token) {
        String s = redisTemplate.opsForValue().get(LOGIN_TOKEN+token);
        return s;
    }

    /**
     * 登录页
     * @param model
     * @param url
     * @param cookie
     * @return
     */
    @GetMapping(value = "/login.html")
    public String loginPage( Model model,
                            @RequestParam("redirect_url") String url,
                            @CookieValue(value = "sso_token", required = false) String cookie) {
        if (!StringUtils.isEmpty(cookie)){
            return "redirect:" + url + "?token=" + cookie;
        }
        model.addAttribute("url", url);
        return "login";
    }

    /**
     * 处理form表单请求
     * @param username
     * @param password
     * @param url
     * @param response
     * @return
     */
    @PostMapping(value = "/doLogin")
    public String doLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          @RequestParam("url") String url,
                          HttpServletResponse response) {
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            //登录成功,返回到之前页面
            //把登录成功的用户在redis存起来
            String uuid = UUID.randomUUID().toString().replace("-", "");
            Cookie ssoToken = new Cookie("sso_token", uuid);
            response.addCookie(ssoToken);
            redisTemplate.opsForValue().set(LOGIN_TOKEN+uuid, username);
            return "redirect:" + url + "?token=" + uuid;
        }
        //失败
        return "login";
    }
}
